<?php
/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

class ChapterController extends Zend_Controller_Action
{

    public function init()
    {        
        $this->stylesBase = $this->view->baseUrl() . '/styles/';
    }
    
    public function preDispatch()
    {
        if(Zend_Auth::getInstance()->hasIdentity())
        {
            switch ($this->getRequest()->getActionName())
            {
                case 'index':
                case 'search':
                case 'add':
                case 'edit':
                case 'delete':
                case 'view':                    
                    break;
                default:
                    $this->_helper->redirector('index', 'index');
                    break;
            }
        }
        else
        {
            switch ($this->getRequest()->getActionName())
            {
                case 'logout':
                    $this->_helper->redirector('index');
                    break;
                default:
                    break;
            }
        } 
    }

    /**
     * Main action, will display all the chapters, as well as let the user search
     * for a chapter by name
     *
     */
    public function indexAction()
    {
        $view   = $this->_getView('Chapters');
        
        // AJAX Search form
        $search = $this->_getChapterSearchForm();
        $search->getElement('searchstring')->setJQueryParam('source', $view->baseUrl('chapter/search'));
        
        // What to display?
        $request = $this->getRequest();        
        if($request->isPost())
        {
            if($search->isValid($request->getPost()))
            {
                $chapter_name   = $search->getValue('chapter_name');
                $chapters       = $this->_getChaptersByName($chapter_name);
                $view->chapters = $chapters;
            }
        }
        else
        {                  
            $view->chapters = $this->_getAllChapters();          
        }
        
        // Finish things up
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        $view->search = $search;
    }
    
    /**
     * This will output a JSON array of Announcement Titles
     */
    public function searchAction()
    {
        // We only need a JSON result, no other output
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        
        // Load the results
        $chapters = $this->_getChaptersByName($this->_getParam('term'));                
        $results = array();    
 
        foreach ($chapters as $chapter) {            
            $results[] = $chapter->Name;
        }
        
        $this->_helper->json($results);
    }
    
    /**
     * This will let you display an edit form
     *
     */
    public function editAction()
    {
        // Set up basics
        $view = $this->_getView('Edit Chapter');
        $form = $this->_getEditChapterForm();
        
        // Are we submitting the form or not?
        if($this->getRequest()->isPost()) 
	{            
            // Get the form data an validate it
            $formData  = $this->_request->getPost();
            if($form->isValid($formData)) 
            {
                // This will only be visible if something goes wrong
                $view = $this->_getView('Fout - Toevoegen');                
                
                // Fetch our mapper
                $mapper = new Application_Model_ChapterMapper();
                
                // Prepare to save
                $values  = $form->getValues();
                $chapter = new Application_Model_Chapter();
                $chapter->Id        = $values['chapter_id'];
                $chapter->Name      = $values['chapter_name'];
                $chapter->BookId    = $values['chapter_book_id'];
                
                // Save
                $mapper->save($chapter);

                // Redirect
                return $this->_helper->redirector('index', 'chapter');             
            }
        }
        else
        {                  
            // Check if we have an ID, if so, populate the form
            $chapter_id = (string)$this->getRequest()->getParam('id');
            $book_id    = (string)$this->getRequest()->getParam('book');
            $chapter = $this->_getChapterById($chapter_id);
            $form->populate(array(
                'chapter_id'            => $chapter->Id,
                'chapter_name'          => $chapter->Name,
                'chapter_book_id'       => $chapter->BookId,
            ));
        }
        
        // Push our form
        $view->form = $form;
    }
    
    /**
     * This will let you delete a chapter
     *
     */
    public function deleteAction()
    {
        $id = (string)$this->getRequest()->getParam('id');
        $chapterMapper = new Application_Model_ChapterMapper();
        $chapterMapper->delete($id);
        $this->_helper->redirector('index', 'chapter');
    }
    
    /**
     * Returns an array of all active chapters
     *
     * @return Array(Application_Model_Chapter)
     *
     */
    private function _getAllChapters()
    {
        $chapterMapper = new Application_Model_ChapterMapper();
        return $chapterMapper->fetchAll();
    }
    
    /**
     * Get the edit form
     *
     * @return Application_Form_EditChapter
     *
     */
    private function _getEditChapterForm()
    {
        return new Application_Form_EditChapter(array(
            'action' => $this->view->baseUrl() . '/chapter/edit/',
            'post'   => 'post',
        ));
    }
    
    /**
     * Fetch a chapter by its ID
     *
     * @param integer $id
     * @return Application_Model_Chapter
     *
     */
    private function _getChapterById($id)
    {
        $chapterMapper = new Application_Model_ChapterMapper();
        return $chapterMapper->fetchById($id);
    }
       
    /**
     * AJAX Search form, search chapter by name
     *
     * @return Application_Form_ChapterSearch
     *
     */
    private function _getChapterSearchForm()
    {
        return new Application_Form_NameSearch(array(
            'action' => $this->view->baseUrl('chapter/index'),
            'method' => 'post',
        ));
    }
    
    /**
     * Get all chapters by (part of) their name/title
     *
     * @return Array(Application_Model_Chapter)
     *
     */
    private function _getChaptersByName($name)
    {
        $chapterMapper = new Application_Model_ChapterMapper();
        return $chapterMapper->fetchByName($name);
    }
    
    /**
     * Get the view
     *
     * @param string $title
     * @return Zend_View
     *
     */
    private function _getView($title)
    {
        $view = $this->view;
        $view->title = $title;
        $view->headTitle($view->title, 'PREPEND');

        return $view;
    }


}



